package com.teradata.config;

import com.teradata.callback.CallBack;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 *@project chinabond-edb
 *@description 任务上下文实现
 *
 *@errorcode
 *          SystemException</br>
 *
 *@author
 *       2018-08-24 13:50 huzy Create 1.0 <br>
 *
 *@copyright ©2017-2017 中央结算公司，版权所有。
 */
public class TaskContextImpl implements TaskContext {

    private AsyncConfiguration asyncConfiguration;

    private String taskGrpName;


    private final BlockingQueue<Object[]> box = new ArrayBlockingQueue<>(100);

    private final AtomicBoolean lock = new AtomicBoolean(false);

    private volatile long lockTime = 0;
    private volatile long dispatchTime = 0;

    private volatile boolean suspend = false;


    public TaskContextImpl(AsyncConfiguration asyncConfiguration, String taskGrpName){
        this.asyncConfiguration = asyncConfiguration;
        this.taskGrpName = taskGrpName;
    }

    @Override
    public void setTaskGrpName(String taskGrpName) {
        this.taskGrpName = taskGrpName;
    }

    @Override
    public String getTaskGrpName() {
        return taskGrpName;
    }

    @Override
    public void submit(ITask task) {
        submit(task, null);
    }

    @Override
    public void submit(ITask task, CallBack cb) {
        try {
            box.put(cb == null ? new Object[]{this, cb} : new Object[]{this});
            asyncConfiguration.monitor(this);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean lock() {
        boolean ret = lock.compareAndSet(false, true);
        if(ret)
            this.lockTime = System.currentTimeMillis();
        return ret;
    }

    @Override
    public int lockTime() {
        return (int) (this.lockTime <=0 ? 0: System.currentTimeMillis() - this.lockTime);
    }

    @Override
    public void unlock() {
        this.lockTime = 0;
        lock.set(false);
    }

    @Override
    public Object[] poll() {
        return this.box.poll();
    }

    @Override
    public boolean empty() {
        return box.isEmpty();
    }

    @Override
    public int count() {
        return box.size();
    }

    @Override
    public boolean isSuspend() {
        return this.suspend;
    }

    @Override
    public void suspend(boolean flag) {
        this.suspend = flag;
    }

    @Override
    public long getDispatchTime() {
        return dispatchTime;
    }

    @Override
    public void setDispatchTime(long dispatchTime) {
        this.dispatchTime = dispatchTime;
    }
}
